package com.tianjishuju.cimiss.station.station.manager;

import com.google.gson.Gson;
import com.tianjishuju.cimiss.station.station.util.ExcelUtil;
import com.tianjishuju.cimiss.station.station.util.ObjUtil;
import com.tianjishuju.cimiss.station.station.util.RestUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.*;

@Component
public class RealTimeService {
    public static void main(String[] arg) {
        RealTimeService real = new RealTimeService();
        real.findAllDisplayMainSer("57516", "20181010000000");
    }


    public Map<String, Object> findAllDisplayMainSer(String staId, String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        Map<String, Object> rtn = new HashMap<>();
//        Map<String,Object> map = parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime","SURF_CHN_MUL_HOR","Station_ID_C,Lon,Lat,Province,City,Cnty,TEM","times=20181023000000","adminCodes=500000&eleValueRanges=Station_Id_d:57338"));
        //当期气温排序
        rtn.put("tempSort", parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,TEM,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆市&orderBy=TEM:DESC&adminCodes=500000", "limitCnt=30")).get("DS"));
        //降水实况
        rtn.put("rainAuto", parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRE_24h,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆市&orderBy=PRE_1h:DESC&adminCodes=500000", "")).get("DS"));
        //气温实况
        rtn.put("temp", parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,TEM,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆&adminCodes=500000", "")).get("DS"));//&eleValueRanges=Station_Id_d:57338
        //小时降水
        rtn.put("rain", parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRE_1h,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆&adminCodes=500000", "")).get("DS"));//&eleValueRanges=Station_Id_d:57338
        //气,湿,温
        rtn.put("airHumTemp", parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaIdRange", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRS,RHU,TEM,Year,Mon,Day,Hour", "times=" + timeStr, "orderBy=hour:ASC,day:ASC&minStaId=57516&maxStaId=57516", "limitCnt=30")).get("DS"));
        //风速,风向
        rtn.put("windAndDir", parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaIdRange", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,WIN_S_Max,WIN_D_S_Max,WIN_D_INST,WIN_S_INST,Year,Mon,Day,Hour", "times=" + timeStr, "orderBy=hour:ASC,day:ASC&minStaId=57516&maxStaId=57516", "limitCnt=30")).get("DS"));
        //能见度（长江航道 读取excel）
        rtn.put("visibility", parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaID", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,VIS,Year,Mon,Day,Hour", "times=" + time, "staIds=A8101,A8500,A8501,A8502,A8503,A8504,A8505,A8506,A8507,A8508,A8509,A8510,A8511,A8512,A8513,A8514,A8515,A8516,A8518,A8519,A8520,A8521,A8525,A8526,A8527", "")).get("DS"));
        //L雷达
        rtn.put("radar", parseJSON2Map(getRealTimeData("getUparEleByTime", "UPAR_CHN_MUL_SEC", "Year_Data,Mon_Data,Day_Data,Hour_Data,Station_Id_C,Year,Mon,Day,Hour,Min,Second,TEM,RHU,WIN_D,WIN_S,GPH", "times=" + time, "eleValueRanges=Station_Id_C:57516;GPH:(,1500)", "")).get("DS"));
        return rtn;
    }

    //当期气温排序
    public List<Map<String, Object>> getRealTempSort(String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");


        Map<String, Object> getSurfEleInRegionByTime = parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,TEM,Year,Mon,Day,Hour", "times=" + timeStr, "eleValueRanges=City:重庆市&orderBy=TEM:DESC&adminCodes=500000", "limitCnt=30"));
        Object ds = getSurfEleInRegionByTime.get("DS");
        //  return parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,TEM,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆市&orderBy=TEM:DESC&adminCodes=500000", "limitCnt=30")).get("DS");
        return (List<Map<String, Object>>) ds;
    }

    //降水实况
    public Object getRealRinAuto(String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        return parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRE_24h,Year,Mon,Day,Hour", "times=" + timeStr, "eleValueRanges=City:重庆市&orderBy=PRE_1h:DESC&adminCodes=500000", "")).get("DS");
    }

    //气温实况
    public Object getRealTemp(String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        return parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,TEM,Year,Mon,Day,Hour", "times=" + times, "eleValueRanges=City:重庆&adminCodes=500000", "")).get("DS");//&eleValueRanges=Station_Id_d:57338
    }

    //小时降水
    public Object getRealRain(String time) {
        Map<String, Integer> resultMap = new HashMap<>();

        resultMap.put(RainGrade.LightRain.getDescription(), 0);
        resultMap.put(RainGrade.ModerateRain.getDescription(), 0);
        resultMap.put(RainGrade.HaleWater.getDescription(), 0);
        resultMap.put(RainGrade.Storm.getDescription(), 0);

        List<Map<String, Object>> list = (List<Map<String, Object>>) parseJSON2Map(getRealTimeData("getSurfEleInRegionByTime", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRE_1h,Year,Mon,Day,Hour", "times=" + time, "eleValueRanges=City:重庆&adminCodes=500000", "")).get("DS");//&eleValueRanges=Station_Id_d:57338
        for (Map<String, Object> map : list) {
            Double pre_1h = Double.parseDouble(map.get("PRE_1h").toString());
            String rainGrade = RainGrade.getRainGrade(pre_1h);
            if (ObjUtil.isNotEmpty(rainGrade)) {
                Integer num = resultMap.get(rainGrade);
                ++num;
                resultMap.put(rainGrade, num);
            }
        }
        return resultMap;
    }

    //气,湿,温
    public Object getRealRirHumTemp(String time, String staId) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        return parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaIdRange", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,PRS,RHU,TEM,Year,Mon,Day,Hour", "times=" + timeStr, "orderBy=hour:ASC,day:ASC&minStaId=" + staId + "&maxStaId=" + staId, "limitCnt=30")).get("DS");
    }

    //风速,风向
    public Object getRealWindAndDir(String time, String staId) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        return parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaIdRange", " SURF_CHN_MUL_HOR_N", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,WIN_S_Max,WIN_D_S_Max,WIN_D_INST,WIN_S_INST,Year,Mon,Day,Hour", "times=" + timeStr, "orderBy=hour:ASC,day:ASC&minStaId=" + staId + "&maxStaId=" + staId, "limitCnt=30")).get("DS");
    }

    //能见度（长江航道 读取excel）
    public Object getRealVisibility(String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        //staIds=A8101,A8500,A8501,A8502,A8503,A8504,A8505,A8506,A8507,A8508,A8509,A8510,A8511,A8512,A8513,A8514,A8515,A8516,A8518,A8519,A8520,A8521,A8525,A8526,A8527"
        String staIds = getIdsByExcel();
        return parseJSON2Map(getRealTimeData("getSurfEleByTimeAndStaID", "SURF_CHN_MUL_HOR", "Station_Name,Station_Type,Lon,Lat,Province,City,Cnty,VIS,Year,Mon,Day,Hour", "times=" + time, "staIds=" + staIds, "")).get("DS");
    }

    //L雷达
    public Object getRealRadar(String time) {
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++)
            times.add(time.substring(0, 8) + (i < 10 ? "0" + i + "0000" : i + "0000"));
        String timeStr = StringUtils.join(times.toArray(), ",");
        //L雷达                                                 interfaceId=getUparEleByTime&dataCode=UPAR_GLB_MUL_FTM&elements=TEM,DPT,WIN_S&times=20181209000000&limitCnt=30&dataFormat=html
        return parseJSON2Map(getRealTimeData("getUparEleByTime", "UPAR_GLB_MUL_FTM", "Year_Data,Mon_Data,Day_Data,Hour_Data,Station_Id_C,Year,Mon,Day,Hour,Min,Second,TEM,DPT,WIN_S,PRS_HWC", "times=" + time, "", "limitCnt=30")).get("DS");
    }

    public Object getExelSite() {
        List<Map<String, Object>> listSite = new ArrayList<>();
        try {
            // 取相对路径  风速、风向、三线图站点信息.xls
            URL resource = this.getClass().getResource("/");
            File excelFile = new File(resource.getPath() + "风速、风向、三线图站点信息.xls");// 创建文件对象
            ExcelUtil.checkExcelVaild(excelFile);
            FileInputStream in = new FileInputStream(excelFile); // 文件流
            Workbook workbook = ExcelUtil.getWorkbok(in, excelFile);
            int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
            Sheet sheet = workbook.getSheetAt(0);   // 遍历Sheet


            // 为跳过第一行目录设置count
            int count = 0;
            for (Row row : sheet) {
                // 跳过第一和第二行的目录
                if (count < 1) {
                    count++;
                    continue;
                }
                //如果当前行没有数据，跳出循环
                if (row.getCell(0).toString().equals("")) {
                    continue;
                }
                Cell cellName = row.getCell(0);
                Object siteName = ExcelUtil.getValue(cellName);
                Cell cellValue = row.getCell(2);
                Object siteNumber = ExcelUtil.getValue(cellValue);
                Map<String, Object> mapSite = new HashMap<>();
                mapSite.put("siteName", siteName);
                mapSite.put("siteNumber", Double.parseDouble(siteNumber.toString()));
                listSite.add(mapSite);
            }
            Collections.sort(listSite, new Comparator<Map<String, Object>>() {

                @Override
                public int compare(Map<String, Object> site1, Map<String, Object> site2) {
                    Double siteNumber1 = Double.parseDouble(site1.get("siteNumber").toString());
                    Double siteNumber2 = Double.parseDouble(site2.get("siteNumber").toString());
                    return siteNumber1.compareTo(siteNumber2);
                }

            });
            return listSite;
        } catch (Exception e) {
            System.out.println(" RealTimeService ： Excel analysis failed");
            e.printStackTrace();

        }
        return "";
    }

    /*
     * rest访问数据
     */
    public String getRealTimeData(String interfaceId, String code, String attribute, String time, String condition, String limit) {
        String params = "userId=BECQ_XXZX_show" +
                "&pwd=yxjkk" +
                "&interfaceId=" + interfaceId +
                "&dataCode=" + code +
                "&elements=" + attribute +
                "&" + time +
                "&" + condition +
                "&" + limit +
                "&dataFormat=json"; /* 1.4 序列化格式 */
        /* 2. 调用接口 */
        RestUtil restUtil = new RestUtil();
        String rstData = restUtil.getRestData(params);
        return rstData;
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(jsonStr, map.getClass());
        return map;
    }

    /**
     * 获取excel ids
     */
    public String getIdsByExcel() {
        StringBuilder ids = new StringBuilder();
        try {
            // 取相对路径  长江航道能见度站点信息.xlsx
            URL resource = this.getClass().getResource("/");
            File excelFile = new File(resource.getPath() + "长江航道能见度站点信息.xlsx");// 创建文件对象
            ExcelUtil.checkExcelVaild(excelFile);
            FileInputStream in = new FileInputStream(excelFile); // 文件流
            Workbook workbook = ExcelUtil.getWorkbok(in, excelFile);
            int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
            Sheet sheet = workbook.getSheetAt(0);   // 遍历Sheet
            // 为跳过第一行目录设置count
            int count = 0;
            for (Row row : sheet) {
                // 跳过第一和第二行的目录
                if (count < 1) {
                    count++;
                    continue;
                }
                //如果当前行没有数据，跳出循环
                if (row.getCell(0).toString().equals("")) {
                    continue;
                }
                Cell cell = row.getCell(0);
                Object value = ExcelUtil.getValue(cell);
                ids.append(value).append(",");
            }

            return ids.substring(0, ids.length() - 1);
        } catch (Exception e) {
            System.out.println(" RealTimeService ： Excel analysis failed");
            e.printStackTrace();
        }
        return "";
    }
}
